package com.lancoo.answer.view.fragment.translate;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lancoo.answer.R;
import com.lancoo.answer.model.AnswerConstant;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Child;
import com.lancoo.answer.model.bean.ItemAsk;
import com.lancoo.answer.model.bean.Ques;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.ui.ques.SpliteLayoutFragment;
import com.lancoo.answer.ui.ques.quesBody.TranslationQuseBodyFragment;
import com.lancoo.answer.widget.combinationView.QueseBodyView;
import com.rxjava.rxlife.RxLife;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2021/12/10 10:55
 * Description:篇章翻译作答fragment
 */
public class TranslateChapterAnswerFragment extends Fragment {

    private static final String TAG = "TranslateChapterAnswerF";
    private Child child;
    private TranslateChapterAdapter mAdapter;
    private RecyclerView recyclerView;
    private int currentFocusIndex;
    private QueseBodyView queseBodyView;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ev_fragment_translate_chapter, container, false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    /**
     * @param kindIndex       List<Type>题型下标
     * @param queseIndex      List<Type>大题下标
     * @param smallQueseIndex List<Type>小题下标
     * @param answerType      作答类型 0-识别成英文，1-识别成中文
     * @return fragment
     */
    public static Fragment loadQueseFragment(int kindIndex, int queseIndex,
                                             int smallQueseIndex, int answerType) {
        TranslateChapterAnswerFragment queseFragment = new TranslateChapterAnswerFragment();
        Bundle mBundle = new Bundle();
        mBundle.putInt("kindIndex", kindIndex);
        mBundle.putInt("queseIndex", queseIndex);
        mBundle.putInt("smallQueseIndex", smallQueseIndex);
        mBundle.putInt("answerType", answerType);
        queseFragment.setArguments(mBundle);
        return queseFragment;
    }

    private void initView(View view) {
        if(getArguments()==null){
            return;
        }
        int kindIndex = getArguments().getInt("kindIndex");
        int queseIndex = getArguments().getInt("queseIndex");
        int smallQueseIndex = getArguments().getInt("smallQueseIndex");
        if(ConstantBean.Companion.getConstantExamBean()==null){
            return;
        }
        List<Type> kindBeanListk = ConstantBean.Companion.getConstantExamBean().getTypeList();
        if(kindBeanListk==null||
                kindBeanListk.get(kindIndex).getQuesList()==null){
            return;
        }
        List<Ques> quesList = kindBeanListk.get(kindIndex).getQuesList();
        if(quesList==null){
            return;
        }
        Ques ques = quesList.get(queseIndex);
        if(ques.getChildList()==null){
            return;
        }
        child = ques.getChildList().get(smallQueseIndex);
        queseBodyView = view.findViewById(R.id.quese_body_view);
        queseBodyView.setEnableShowChildAsk(false);
        queseBodyView.initData(child);
        if(child.getItemList()==null||
                child.getItemList().get(0)==null){
            return;
        }
        final List<ItemAsk> itemAskList = child.getItemList().get(0).getItemAskList();
        recyclerView = view.findViewById(R.id.recycler_view);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        int answerType = getArguments().getInt("answerType");
        mAdapter = new TranslateChapterAdapter(itemAskList, answerType,child);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setCallBack(new TranslateChapterAdapter.OnStuAnswerUpdateCallBack() {
            @Override
            public void updateCallBack() {
                Observable.create((ObservableOnSubscribe<String>) emitter -> {
                    if (child == null||child.getItemList()==null||
                            itemAskList==null) {
                        return ;
                    }
                    StringBuilder stringBuilder = new StringBuilder();
                    for (ItemAsk itemAsk : itemAskList) {
                        if (!TextUtils.isEmpty(itemAsk.getStuAnswer())) {
                            stringBuilder.append(itemAsk.getStuAnswer());
                            stringBuilder.append(AnswerConstant.TRANSLATION_APPEND_CHAR);
                        }
                    }
                    child.getItemList().get(0).setStuAnswer(stringBuilder.toString().trim());
                }).subscribeOn(Schedulers.io()).subscribe();
            }

            @Override
            public void onClickItemIndex(int itemIndex) {
                currentFocusIndex=itemIndex;
                Log.e(TAG,"onClickItemIndex:"+itemIndex);
                if(getParentFragment() instanceof SpliteLayoutFragment){
                    FragmentManager childFragmentManager = (getParentFragment()).getChildFragmentManager();
                    Fragment fragmentByTag = childFragmentManager.findFragmentByTag(SpliteLayoutFragment.TAG);
                    if(fragmentByTag instanceof TranslationQuseBodyFragment){
                        ((TranslationQuseBodyFragment)fragmentByTag).onClickItemIndex(0,itemIndex);
                    }

                }

            }
        });
    }

    //todo 通知题干当前选择的第几个作答框，
    public void setChooseCallback() {

    }

    /**
     * 选中下标itemIndex的分句作答
     * @param itemIndex index
     */
    public void chooseClausesItemIndex(int itemIndex){
        if(recyclerView!=null){
            recyclerView.smoothScrollToPosition(itemIndex);
            Single.timer(200, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .as(RxLife.as(this))
                    .subscribe(aLong -> {
                        mAdapter.localUpdate(itemIndex);
                    });
        }
    }

    public void updateKeyboardShowState(boolean isShow){
        if(isShow&&recyclerView!=null){
            chooseClausesItemIndex(currentFocusIndex);
        }
    }

    /**
     * 关闭音频作答
     */
    public void closeAudioAnswer(){
        if(mAdapter==null){
            return;
        }
        mAdapter.closeAudioAnswer(currentFocusIndex);
    }

    public void adjustFontSize(){
        if(mAdapter==null){
            return;
        }
        mAdapter.notifyDataSetChanged();
    }

    public void markQuestion(){
        Log.e("markQuestion","进来了");
        if(mAdapter==null){
            return;
        }
        mAdapter.markQuestion();
    }
}
